import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcom from '../components/Welcom.vue'
import AddAgent from '../components/agent/AddAgent.vue'
import Apportion from '../components/agent/Apportion.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcom',
    children: [
      {
        path: '/welcom',
        component: Welcom
      },
      {
        path: '/addAgent',
        component: AddAgent
      },
      {
        path: '/apportion',
        component: Apportion
      },
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由添加 导航守卫
router.beforeEach((to, form, next) => {
  // to 将要跳转去哪里
  // form 是从哪里跳转过来
  // next()放行 next('/login')是强制跳转
  if (to.path === '/login') return next()
  // 获取token 判断是否登录状态
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
